<?php
/**
 * 用户
 */

use app\config\Db;
use Core\Enums\ErrorEnum;
use Core\Result\Result;
use Core\Utils\Utils;
use app\config\Redis;
use Core\Common\Common;
use GuzzleHttp\Client;


/**
 * 退出登录 TODO
 * @param $data
 * @return void
 */
function logout($data)
{
    $redis = new Redis();
    $user_id = Common::getUser_id($data);
    $redis->delKeys("{$user_id}_token");
    Result::success();
}

/**
 * 用户信息 TODO
 * @param $data
 * @return void
 * @throws \think\Exception
 */
function info($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $userInfo = $db->find("select user_id,mobile,email,nickname,avatar,level,sex,real_name,region_code,user_group,cloud_bean,birth_bean,assist_bean,description,real_name_authentication,certify_id,is_valid,birth from `user_info` where user_id=$user_id limit 1");
    if (empty($userInfo)) Result::error("用户信息错误，请退出重新登陆");
    //用户常住地名称
    $userInfo['region_name'] = '暂无';
    if (!empty($userInfo['region_code'])) {
        $regionInfo = $db->find("select `region_path` from `ysmz_region` where `region_id`={$userInfo['region_code']} limit 1");
        if (isset($regionInfo['region_path'])) {
            $regionAdd = $db->query("select `region_name` from `ysmz_region` where `region_id` in ({$regionInfo['region_path']})");
            $regionAdd = array_column($regionAdd, 'region_name');
            $userInfo['region_name'] = implode(' ', $regionAdd);
        }
    }
    $userInfo["cloud_bean"] = floatval($userInfo["cloud_bean"]);
    $userInfo["birth_bean"] = floatval($userInfo["birth_bean"]);
    $userInfo["assist_bean"] = floatval($userInfo["assist_bean"]);
    Result::success($userInfo);
}
/**
 * 用户拓展信息 TODO
 * @param $data
 * @return void
 * @throws \think\Exception
 */
function infoExt($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $userInfo = $db->find("select user_id,cloud_bean,birth_bean,assist_bean from `user_info` where user_id=$user_id limit 1");
    $collectCount = $db->find("select count(c.id) as count from `user_goods_collect` as c inner join ysmz_shop_goods as g on c.g_id = g.goods_id  where c.`user_id` =$user_id and g.is_delete=0 and g.is_adopt=1 and g.is_top=1 ")['count'];
    $orderCount = $db->find("select count(order_id) as count from `ysmz_shop_goods_order` where `user_id` =$user_id and `comment_status`=0 and `order_state`=3")['count'];
    $time = time();
    $couponCount = $db->find("select count(id) as count from `user_coupon` where `user_id` =$user_id and `used_time`=0 and `start_date`>$time and `end_date`< $time")['count'];
    $browseCount = $db->find("select count(c.id) as count from `user_goods_browse` as c inner join ysmz_shop_goods as g on c.g_id = g.goods_id  where c.`user_id` =$user_id and g.is_delete=0 and g.is_adopt=1 and g.is_top=1 ")['count'];
    $res["collectCount"] = $collectCount ?? 0;
    $res["orderCount"] = $orderCount ?? 0;
    $res["couponCount"] = $couponCount ?? 0;
    $res["browseCount"] = $browseCount ?? 0;
    $res["cloud_bean"] = $userInfo["cloud_bean"] ?? 0;
    $res["birth_bean"] = $userInfo["birth_bean"] ?? 0;
    $res["assist_bean"] = $userInfo["assist_bean"] ?? 0;
    Result::success($res);
}
/**
 * 用户流水 TODO
 * @param $data
 * @param $data_src             流水类型【1云豆2微信3生日豆4帮扶豆】
 * @return void
 */
function funds($data)
{
    $user_id = Common::getUser_id($data);
    $page = $data["page"];
    $limit = $data["limit"];
    $db = new Db();
    $fundsList = $db->query("select balance,data_remarks,data_id,update_type,data_src,create_time as date_time from user_balance_detail where user_id=$user_id order by id desc,create_time desc limit $page,$limit");
    foreach ($fundsList as $k => $v) {
        $fundsList[$k]["payment"] = getPayment($v["data_src"]);
    }
    Result::success($fundsList);
}

/**
 * 账户注销 TODO
 * @param $data
 * @return void
 */
function cancellation($data)
{
    $sms_code = $data["sms_code"];
    $user_id = Common::getUser_id($data);
    if (empty($sms_code)) Result::error("请输入验证码");
    $db = new Db("host");
    $userInfo = $db->find("select mobile,email from user_info  where user_id=$user_id limit 1");
    $cache = new Redis();
    $cacaheSmsCode = $cache->get("zxsms_code_{$userInfo['mobile']}");
    $commonCode = Common::config('config')['generalVerify']['code'];
    if ($sms_code != $commonCode && $cacaheSmsCode != $sms_code) Result::error("验证码错误");
    $lastAccountInfo = $db->find("select mobile from user_info where mobile like '100%' order by mobile desc limit 1");
    $lastAccount = 10000000000;
    if (isset($lastAccountInfo['mobile'])) $lastAccount = $lastAccountInfo['mobile'] + 1;
    $db->startTrans();
    try {
        $clearUserAccountInformation = "update user_extra_info uei,user_authentication ua,user_info ui set uei.old_mobile=ua.account,uei.is_valid=0,ua.mobile=$lastAccount,ui.mobile=$lastAccount,ui.email=null,ui.sex=null,ui.real_name=null,ui.id_card=null,ui.real_name_authentication=0,ua.enable=0,ua.account=$lastAccount where uei.user_id=ua.id and ui.user_id=ua.id and ua.id=$user_id";
        if (!$db->save($clearUserAccountInformation)) Common::exception('用户信息清除失败！');
        $cache->setEx("{$user_id}_token", 1, '');
        $db->commit();
        Result::success("注销成功");
    } catch (\Exception $e) {
        $db->rollback();
        Result::error($e->getMessage());
    }
}

/**
 * 用户信息修改 TODO
 * @param $data
 * @return void
 */
function infoEdit($data)
{
    $user_id = Common::getUser_id($data);
    $nickname = $data["nickname"];
    $avatar = $data["avatar"];
    $type = $data["type"];
    $password_old = $data["password_old"];
    $password_new = $data["password_new"];
    $password_repeat = $data["password_repeat"];
    $birth = $data["birthday"];
    $db = new Db("host");
    switch ($type) {
        case 1:
            if (empty($nickname)) Result::error("请输入昵称");
            $upInfo = "昵称生日";
            $userInfo = $db->find("select `nickname`,`birth` from user_info where user_id=$user_id limit 1");
            if (empty($userInfo)) Result::error("用户信息不存在");

            $updata = "`nickname`='$nickname'";
            if(!empty($birth)){
                $birthdayExplode = explode("-", $birth);
                $birthday = $birthdayExplode[1].$birthdayExplode[2];
                $updata .=",`birthday`='$birthday',`birth` = '$birth'";
                if ($userInfo['nickname'] == $nickname && $userInfo['birth'] == $birth) Result::success();
            }else{
                if ($userInfo['nickname'] == $nickname) Result::success();
            }
            break;
        case 2:
            $upInfo = "头像";
            $updata = "`avatar`='$avatar'";
            break;
        case 3:
            $upInfo = "密码";
            if ($password_new !== $password_repeat) Result::error("两次密码输入不一致");
            $userInfo = $db->find("select password from user_authentication where id=$user_id limit 1");
            $userPassword = $userInfo['password'];
            $userInfo['password'] = Common::passwordTh($userInfo['password']);
            if (!password_verify($password_old, $userInfo['password']) && md5($password_old) != $userPassword) Result::error("原密码输入错误");
            $password = password_hash($password_new, PASSWORD_DEFAULT);
            $password = Common::passwordTh($password, 2);
            $updata = "`password`='$password'";
            break;
        default:
            Result::error("非法请求类型");
    }
    $db->startTrans();
    try {
        $upUserInfo = "update user_info set $updata where user_id=$user_id";
        if ($type == 3) $upUserInfo = "update user_authentication set $updata where id=$user_id";
        if (!$db->save($upUserInfo)) Common::exception("{$upInfo}更新失败");
        $db->commit();
        Result::success();
    } catch (\Exception $e) {
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 用户实名认证 TODO
 * @param $data
 * @return array
 */
function certification($data)
{
    $id_card = $data["id_card"];
    $real_name = $data["real_name"];
    $user_id = Common::getUser_id($data);
    if(empty($id_card) || empty($real_name)){
        Result::error("请输入姓名和身份证号");
    }
    $db = new Db("host");
    $userInfo = $db->find("select user_id,mobile,email,real_name,id_card,real_name_authentication,create_date from user_info where user_id=$user_id limit 1");
    if($userInfo["real_name_authentication"] == 1){
        Result::error("当前账号已认证，请勿重复提交！");
    }
    $mobile = $userInfo['mobile'];
    //接入认证
    $host = "https://bjf.market.alicloudapi.com";
    $path = "/efficient/cellphone/post";
    $appcode = "0a2286f6d2254e74a4133bc8e3cef016";
    $headers = [
        "Authorization" => "APPCODE " . $appcode,
        "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"
    ];
    $real_name = urlencode($real_name);
    $bodys = "mobile=$mobile&idCard=$id_card&realName=$real_name";
    $url = $host . $path;
    $client = new Client();
    $response = $client->post($url, [
        'headers' => $headers,
        'body' => $bodys
    ]);
    $statusCode = $response->getStatusCode();
    if($statusCode == 200){
        $content = $response->getBody()->getContents();
        $json_decode = json_decode($content, true);
        if($json_decode["result"]["VerificationResult"] == -1){
            Result::error("信息不匹配,认证失败");
        }
        if($json_decode["result"]["VerificationResult"] == 0){
            Result::error("系统无记录,认证失败");
        }
    }
    $upUser = "update `user_info` set `real_name` = '$data[real_name]',`id_card` = '$id_card',`real_name_authentication` = 1 where `user_id` = $user_id";
    $db->startTrans();
    try {
        if (!$db->save($upUser)) Common::exception('用户更新失败');
        $db->commit();
        Result::success();
    } catch (\Exception $e) {
        $db->rollback();
        Result::error('认证失败.' . $e->getMessage());
    }
}
/**
 * 重置交易密码 TODO
 * @param $userTokenInfo
 * @return void
 */
function tradePwd($data)
{
    $trade_password = $data["trade_password"];
    $password_repeat = $data["password_repeat"];
    $sms_code = $data["sms_code"];
    $datetime = date("Y-m-d H:i:s",time());
    $user_id = Common::getUser_id($data);
    if(empty($trade_password) || empty($password_repeat) || empty($sms_code)){
        Result::error("请输入完整参数");
    }
    if(strlen($trade_password) != 6 || strlen($password_repeat) != 6){
        Result::error("密码长度6个数字");
    }
    if ($trade_password != $password_repeat) Result::error("两次密码输入不一致");
    $db = new Db("host");
    $userInfo = $db->find("select `mobile` from `user_info`  where `user_id`=$user_id limit 1");
    $redis = new Redis();
    $cache_sms_code = $redis->get("sms_tra_login_{$userInfo['mobile']}");
    $generalVerify = Common::config('config')['generalVerify']['code'];
    if ($sms_code != $generalVerify && $cache_sms_code != $sms_code) Result::error("验证码错误");
    $password = password_hash($trade_password, PASSWORD_DEFAULT);
    $password = Common::passwordTh($password, 2);
    $upUserExtra = "update `user_extra_info` set `trade_password`='$password',`last_modify_date`='$datetime' where `user_id`=$user_id";
    if (!$db->save($upUserExtra)) Result::error("交易密码重置失败");
    Result::success("ok");
}

/**
 * 地址列表 TODO
 * @param $data
 * @return void
 */
function addressList($data)
{
    $db = new Db();
    $user_id = Common::getUser_id($data);
    $addrList = $db->query("select * from receive_address where user_id=$user_id and data_flag=1 order by create_date desc");
    Result::success($addrList);
}

/**
 * 默认地址 TODO
 * @param $data
 * @return void
 */
function defaultAddress($data)
{
    $db = new Db();
    $user_id = Common::getUser_id($data);
    $defaultAdd = $db->find("select * from `receive_address` where user_id=$user_id and data_flag=1 and is_default=1 order by last_modify_date desc limit 1");
    Result::success($defaultAdd);
}

/**
 * 地址添加 TODO
 * @param $data
 * @return void
 */
function addressAdd($data)
{
    $time = time();
    $datetime = date('Y-m-d H:i:s', $time);
    $consignee_name = $data['consignee_name'];
    $consignee_mobile = $data['consignee_mobile'];
    $area_path = $data['area_path'];
    $region_code = $data['region_code'];
    $detail_address = $data['detail_address'];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    if (empty($consignee_name) || empty($consignee_mobile) || empty($area_path) || empty($region_code) || empty($detail_address)) Result::error("请输入完整的地址信息");
    if (!Utils::phoneChecking($consignee_mobile)) Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
    $addressInfo = $db->find("select * from receive_address where user_id=$user_id and data_flag=1 limit 1");
    $is_default = 0;
    if (!$addressInfo) $is_default = 1;
    $addAddress = "insert into receive_address(user_id,consignee_name,consignee_mobile,area_path,region_code,detail_address,is_default,create_date) values ($user_id,'$consignee_name','$consignee_mobile','$area_path','$region_code','$detail_address',$is_default,'$datetime')";
    if (!$db->save($addAddress)) Result::error("地址添加失败");
    Result::success();
}

/**
 * 地址修改 TODO
 * @param $data
 * @return void
 */
function addressEdit($data)
{
    $user_id = Common::getUser_id($data);
    $id = $data['id'];
    $consignee_name = $data['consignee_name'];
    $consignee_mobile = $data['consignee_mobile'];
    $area_path = $data['area_path'];
    $region_code = $data['region_code'];
    $detail_address = $data['detail_address'];
    $is_default =  $data['is_default'];
    if (empty($id) || $id == 0) Result::error("请上传地址ID");
    if (!Utils::phoneChecking($consignee_mobile)) Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
    $db = new Db("host");
    if ($is_default && $is_default == 1) {
        $upIsDefault = "update receive_address set is_default=0 where id<>$id and user_id=$user_id";
        $db->save($upIsDefault);
        $is_default = ",is_default=1";
    }else{
        $is_default='';
    }
    $time = time();
    $datetime = date('Y-m-d H:i:s', $time);
    $upAddr = "update `receive_address` set `consignee_name`='$consignee_name',`consignee_mobile`='$consignee_mobile',`area_path`='$area_path',`region_code`='$region_code',detail_address='$detail_address',`last_modify_date` = '$datetime' $is_default where `id`= $id and `user_id`= $user_id";
    if (!$db->save($upAddr)) Result::error("地址更新失败");
    Result::success();
}

/**
 * 地址删除 TODO
 * @param $data
 * @return void
 */
function addressDel($data)
{
    $id = $data['id'];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $addrInfo = $db->find("select * from `receive_address` where `id`=$id and `user_id`=$user_id and `data_flag`=1 limit 1");
    if (!$addrInfo) Result::error("地址信息不存在");
    if ($addrInfo['is_default'] == 1) Result::error("您删除的是默认地址，请先修改默认地址！");
    $upAddr = "update `receive_address` set `data_flag`=0 where `id`=$id and `user_id`=$user_id and `data_flag`=1";
    if (!$db->save($upAddr)) Result::error("地址删除失败");
    Result::success();
}
/**
 * 商品收藏 TODO
 * @param $data
 * @return void
 */
function productCollection($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $goodsInfo = $db->query("select goods_id,category_id,shop_id,`name`,goods_type,title,old_price,sell_price,game_points,img_id,hits,sales_volume,unreal_sales_volume,sg.create_time from `user_goods_collect` as ugc inner join `ysmz_shop_goods` as sg on ugc.g_id = sg.goods_id where ugc.`user_id` = $user_id and `is_delete`=0 and `is_adopt`=1 and `is_top` = 1 order by ugc.`create_date` desc");
    if(empty($goodsInfo)){
        Result::success();
    }
    $imgIds = implode(',', array_column($goodsInfo, 'img_id', 'img_id'));
    $categoryIds = implode(',', array_column($goodsInfo, 'category_id'));
    $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($imgIds)");
    foreach ($fileInfo as $k => $v) {
        $fileInfo[$k]['file_url'] = Common::fileUrl($v);
    }
    $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    $categoryInfo = $db->query("select category_id,category_name from ysmz_shop_category where category_id in($categoryIds)");
    $categoryInfo = array_column($categoryInfo, 'category_name', 'category_id');
    foreach ($goodsInfo as $k => $v) {
        $goodsInfo[$k]['img_url'] = $fileInfo[$v['img_id']] ?? '';
        $goodsInfo[$k]['category_name'] = $categoryInfo[$v['category_id']] ?? '(未分类)';
    }
    Result::success($goodsInfo);
}
/**
 * 帮助中心 TODO
 * @param $data
 * @return void
 */
function help($data)
{
    $db = new Db();
    $help = $db->query("select help_id,name,`icon`,create_time from ysmz_help where `state` = 1 order by `sort` desc");
    $helpInfo = $db->query("select id,title,content,create_time from ysmz_help_info where `state` = 1 and is_show = 1 order by `sort` desc");
    $res["help"] = $help;
    $res["helpShow"] = $helpInfo;
    Result::success($res);
}
/**
 * 帮助中心列表 TODO
 * @param $data
 * @return void
 */
function helpList($data)
{
    $help_id = $data["help_id"];
    $db = new Db();
    $helpInfo = $db->query("select id,title,content,create_time from ysmz_help_info where `help_id` = $help_id and `state` = 1 order by `sort` desc");
    Result::success($helpInfo);
}
/**
 * 浏览记录 TODO
 * @param $data
 * @return void
 */
function browsingHistory($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $goodsInfo = $db->query("select ugb.id,goods_id,category_id,shop_id,`name`,goods_type,title,old_price,sell_price,game_points,img_id,hits,sales_volume,unreal_sales_volume,sg.create_time from `user_goods_browse` as ugb inner join `ysmz_shop_goods` as sg on ugb.g_id = sg.goods_id where ugb.`user_id` = $user_id and `is_delete`=0 and `is_adopt`=1 and `is_top` = 1 order by ugb.create_date desc");
    if(empty($goodsInfo)){
        Result::success();
    }
    $imgIds = implode(',', array_column($goodsInfo, 'img_id', 'img_id'));
    $categoryIds = implode(',', array_column($goodsInfo, 'category_id'));
    $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($imgIds)");
    foreach ($fileInfo as $k => $v) {
        $fileInfo[$k]['file_url'] = Common::fileUrl($v);
    }
    $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    $categoryInfo = $db->query("select category_id,category_name from ysmz_shop_category where category_id in($categoryIds)");
    $categoryInfo = array_column($categoryInfo, 'category_name', 'category_id');
    foreach ($goodsInfo as $k => $v) {
        $goodsInfo[$k]['img_url'] = $fileInfo[$v['img_id']] ?? '';
        $goodsInfo[$k]['category_name'] = $categoryInfo[$v['category_id']] ?? '(未分类)';
    }
    Result::success($goodsInfo);
}
/**
 * 删除浏览记录 TODO
 * @param $data
 * @return void
 */
function delBrowsingHistory($data)
{
    $user_id = Common::getUser_id($data);
    $ids = $data['ids'];
    $db = new Db("host");
    $db->save("delete from `user_goods_browse` where `user_id` = $user_id and `id` in($ids)");
    Result::success();
}
/**
 * 优惠券列表 TODO
 * @param $data
 * @return void
 */
function couponList($data)
{
    $user_id = Common::getUser_id($data);
    $type = $data["type"];
    $time = time();
    switch ($type){
        case 1: $where = " and `order_id` =0 and `start_date` < $time and `end_date` > $time";break;//可用优惠券
        case 2: $where = " and `order_id` >0 and (`start_date` > $time or `end_date` < $time)";break;//不可用优惠券
        default:Result::error("类型错误");break;
    }
    $db = new Db();
    $userCouponInfo = $db->query("select `id`,`coupon_id`,`coupon_sn`,`used_time`,`order_id`,`start_date`,`end_date` from `user_coupon` where `user_id` = $user_id $where");
    foreach ($userCouponInfo as $k => $v) {
        $couponInfo = $db->find("select `coupon_name`,`coupon_money`,`coupon_discount`,`coupon_desc`,`coupon_type`,`send_range`,`min_order_amount`,`max_order_amount`,`coupon_unit`,`reduce_type` from `ysmz_coupon` where `coupon_id` = $v[coupon_id]");
        $userCouponInfo[$k]["start_date"] = date("Y-m-d H:i:s", $v["start_date"]);
        $userCouponInfo[$k]["end_date"] = date("Y-m-d H:i:s", $v["end_date"]);
        $list[] = array_merge_recursive($userCouponInfo[$k], $couponInfo);
    }
    Result::success($list);
}
/**
 * 支付方式
 */
function getPayment($type)
{
    switch ($type){
        case 1:$res = "云豆";break;
        case 2:$res = "微信";break;
        case 3:$res = "生日豆";break;
        case 4:$res = "帮扶豆";break;
        default:$res ="未知";break;
    }
    return $res;
}